package ar.edu.itba.it.pdc.protocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import ar.edu.itba.it.pdc.protocol.exception.InvalidPOP3FormatException;
import ar.edu.itba.it.pdc.utils.TempFilesSetup;

public abstract class POP3Request implements IPOP3Request {

	protected static final String CRLF = TempFilesSetup.CRLF;

	protected String command;
	
	public ValidPOP3Request asValid(){
		return (ValidPOP3Request) this;
	}

	public InvalidPOP3Request asInvalid(){
		return (InvalidPOP3Request) this;
	}
	
	public static String createTempString(InputStream stream) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		String input = "", line = "";
		input += reader.readLine();
		
		while(reader.ready() && (line = reader.readLine()) != null)
			input += line;
		
		return input;
	}
	
	public static POP3Request build(String command) throws IOException {
		POP3Request request;
		try {
			request = new ValidPOP3Request(command + CRLF);
		} catch(InvalidPOP3FormatException e){
			request = new InvalidPOP3Request();
		}
		request.setCommand(command + CRLF);
		return request;
	}
	
	private void setCommand(String command){
		this.command = command;
	}
	
	public String getCommand(){
		return this.command;
	}
	
	public long getSize(){
		return getCommand().length();
	}
	
	public void sendTo(Socket socket) throws IOException {
		String command = getCommand();
		System.out.println(command);
		OutputStream output = socket.getOutputStream();
		output.write(command.getBytes());
		output.flush();
	}
}
